using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.IO;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 提示词配置服务实现
    /// </summary>
    public class PromptConfigService : IPromptConfigService
    {
        private readonly IDataStorageService _dataStorage;
        private readonly ILogger<PromptConfigService> _logger;

        public PromptConfigService(IDataStorageService dataStorage, ILogger<PromptConfigService> logger)
        {
            _dataStorage = dataStorage;
            _logger = logger;
        }

        /// <summary>
        /// 获取所有提示词配置
        /// </summary>
        public async Task<List<PromptConfig>> GetAllConfigsAsync()
        {
            try
            {
                var configs = await _dataStorage.GetPromptConfigsAsync();
                return configs.OrderByDescending(c => c.IsDefault)
                    .ThenByDescending(c => c.UpdatedAt)
                    .ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有提示词配置失败");
                throw;
            }
        }

        /// <summary>
        /// 根据ID获取提示词配置
        /// </summary>
        public async Task<PromptConfig?> GetConfigByIdAsync(int id)
        {
            try
            {
                return await _dataStorage.GetPromptConfigAsync(id);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取提示词配置失败，ID: {id}");
                throw;
            }
        }

        /// <summary>
        /// 获取默认提示词配置
        /// </summary>
        public async Task<PromptConfig> GetDefaultConfigAsync()
        {
            try
            {
                var configs = await _dataStorage.GetPromptConfigsAsync();
                var defaultConfig = configs.FirstOrDefault(c => c.IsDefault);

                if (defaultConfig == null)
                {
                    // 如果没有默认配置，创建一个
                    defaultConfig = await CreateDefaultConfigAsync();
                }

                return defaultConfig;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取默认提示词配置失败");
                throw;
            }
        }

        /// <summary>
        /// 保存提示词配置
        /// </summary>
        public async Task<PromptConfig> SaveConfigAsync(PromptConfig config)
        {
            try
            {
                var savedConfig = await _dataStorage.CreatePromptConfigAsync(config);
                _logger.LogInformation($"保存提示词配置成功，ID: {savedConfig.Id}, 名称: {savedConfig.Name}");
                return savedConfig;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"保存提示词配置失败，名称: {config.Name}");
                throw;
            }
        }

        /// <summary>
        /// 更新提示词配置
        /// </summary>
        public async Task<PromptConfig> UpdateConfigAsync(PromptConfig config)
        {
            try
            {
                var updatedConfig = await _dataStorage.UpdatePromptConfigAsync(config);
                _logger.LogInformation($"更新提示词配置成功，ID: {updatedConfig.Id}, 名称: {updatedConfig.Name}");
                return updatedConfig;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新提示词配置失败，ID: {config.Id}");
                throw;
            }
        }

        /// <summary>
        /// 删除提示词配置
        /// </summary>
        public async Task<bool> DeleteConfigAsync(int id)
        {
            try
            {
                var config = await _dataStorage.GetPromptConfigAsync(id);
                if (config == null)
                {
                    return false;
                }

                // 不允许删除默认配置
                if (config.IsDefault)
                {
                    throw new InvalidOperationException("不能删除默认配置");
                }

                await _dataStorage.DeletePromptConfigAsync(id);
                _logger.LogInformation($"删除提示词配置成功，ID: {id}, 名称: {config.Name}");
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除提示词配置失败，ID: {id}");
                throw;
            }
        }

        /// <summary>
        /// 设置默认配置
        /// </summary>
        public async Task<bool> SetDefaultConfigAsync(int id)
        {
            try
            {
                // 清除所有默认标记
                var allConfigs = await _dataStorage.GetPromptConfigsAsync();
                foreach (var config in allConfigs)
                {
                    config.IsDefault = false;
                    await _dataStorage.UpdatePromptConfigAsync(config);
                }

                // 设置新的默认配置
                var targetConfig = allConfigs.FirstOrDefault(c => c.Id == id);
                if (targetConfig != null)
                {
                    targetConfig.IsDefault = true;
                    await _dataStorage.UpdatePromptConfigAsync(targetConfig);

                    _logger.LogInformation($"设置默认提示词配置成功，ID: {id}, 名称: {targetConfig.Name}");
                    return true;
                }

                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"设置默认提示词配置失败，ID: {id}");
                throw;
            }
        }

        /// <summary>
        /// 创建默认配置
        /// </summary>
        public async Task<PromptConfig> CreateDefaultConfigAsync()
        {
            try
            {
                var defaultConfig = new PromptConfig
                {
                    Name = "默认配置",
                    Description = "系统默认的提示词配置",
                    IsDefault = true
                };

                // 使用模型中的默认提示词
                // 这些默认值已经在PromptConfig模型中定义

                var savedConfig = await _dataStorage.CreatePromptConfigAsync(defaultConfig);
                _logger.LogInformation($"创建默认提示词配置成功，ID: {savedConfig.Id}");
                return savedConfig;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建默认提示词配置失败");
                throw;
            }
        }

        /// <summary>
        /// 导出配置到文件
        /// </summary>
        public async Task<bool> ExportConfigAsync(int id, string filePath)
        {
            try
            {
                var config = await GetConfigByIdAsync(id);
                if (config == null)
                {
                    return false;
                }

                var json = JsonConvert.SerializeObject(config, Formatting.Indented);
                await File.WriteAllTextAsync(filePath, json);

                _logger.LogInformation($"导出提示词配置成功，ID: {id}, 文件: {filePath}");
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"导出提示词配置失败，ID: {id}, 文件: {filePath}");
                throw;
            }
        }

        /// <summary>
        /// 从文件导入配置
        /// </summary>
        public async Task<PromptConfig?> ImportConfigAsync(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                {
                    return null;
                }

                var json = await File.ReadAllTextAsync(filePath);
                var config = JsonConvert.DeserializeObject<PromptConfig>(json);

                if (config == null)
                {
                    return null;
                }

                // 重置ID和时间戳
                config.Id = 0;
                config.IsDefault = false;
                config.CreatedAt = DateTime.Now;
                config.UpdatedAt = DateTime.Now;
                config.Name = $"{config.Name}_导入";

                var savedConfig = await SaveConfigAsync(config);
                _logger.LogInformation($"导入提示词配置成功，文件: {filePath}, 新ID: {savedConfig.Id}");
                return savedConfig;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"导入提示词配置失败，文件: {filePath}");
                throw;
            }
        }

        /// <summary>
        /// 验证配置的完整性
        /// </summary>
        public async Task<bool> ValidateConfigAsync(PromptConfig config)
        {
            try
            {
                // 检查必要字段
                if (string.IsNullOrWhiteSpace(config.Name))
                {
                    return false;
                }

                // 检查提示词是否为空
                if (string.IsNullOrWhiteSpace(config.OverallOutlinePrompt) ||
                    string.IsNullOrWhiteSpace(config.WorldSettingPrompt) ||
                    string.IsNullOrWhiteSpace(config.VolumeOutlinePrompt) ||
                    string.IsNullOrWhiteSpace(config.ChapterOutlinePrompt) ||
                    string.IsNullOrWhiteSpace(config.ChapterContentPrompt) ||
                    string.IsNullOrWhiteSpace(config.TimelineUpdatePrompt))
                {
                    return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "验证提示词配置失败");
                return false;
            }
        }

        /// <summary>
        /// 获取配置的预览信息
        /// </summary>
        public async Task<string> GetConfigPreviewAsync(int id)
        {
            try
            {
                var config = await GetConfigByIdAsync(id);
                if (config == null)
                {
                    return "配置不存在";
                }

                return $@"配置名称：{config.Name}
配置描述：{config.Description}
是否默认：{(config.IsDefault ? "是" : "否")}
创建时间：{config.CreatedAt:yyyy-MM-dd HH:mm:ss}
更新时间：{config.UpdatedAt:yyyy-MM-dd HH:mm:ss}

提示词统计：
- 全书大纲：{config.OverallOutlinePrompt.Length} 字符
- 世界设定：{config.WorldSettingPrompt.Length} 字符
- 卷宗大纲：{config.VolumeOutlinePrompt.Length} 字符
- 章节细纲：{config.ChapterOutlinePrompt.Length} 字符
- 章节正文：{config.ChapterContentPrompt.Length} 字符
- 时间线更新：{config.TimelineUpdatePrompt.Length} 字符";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取提示词配置预览失败，ID: {id}");
                return "获取预览失败";
            }
        }
    }
}
